package com.xindaoapp.happypet.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BaiDuLocationManager;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter;
import com.xindaoapp.happypet.entry.Location;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.utils.ProgressHUD;

/**
 * 发帖时，勾选显示附近的地址
 * 
 * @author Yangqing
 * 
 */
public class NearLoationActivity extends BaseActivity {

    private ListView mList;
    private BaiDuLocationManager locationManager;
    private Location location;
    private final int currentPage = 1;
    private GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用

    // private MKSearch mMKSearch = null;



    @Override
    protected int getContentViewResId() {
        return R.layout.layout_nearloation;
    }

    @Override
    protected void initViews() {

        setTopBarTitle("附近的地址");
        locationManager = BaiDuLocationManager.getInstance(NearLoationActivity.this);
        locationManager.isLoadFirst = true;
        // 初始化搜索模块，注册事件监听
        locationManager.start();
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(mOnGetGeoCoderResultListener);
        mList = (ListView) findViewById(R.id.mList);

        locationName = getIntent().getStringExtra("locationName");
    }

    @Override
    protected void onResume() {
        super.onResume();
        // onLoadDatas();
    }

    @Override
    protected void onLoadDatas() {

        progressDialog = ProgressHUD.show(NearLoationActivity.this, "正在获取位置...", true, true, null);



        PoiInfo poiInfo = new PoiInfo();
        poiInfo.name = "不显示位置";
        // PoiInfo poiInfo1 = new PoiInfo();
        // poiInfo1.name = "北京";
        List<PoiInfo> results = new ArrayList<PoiInfo>();
        results.add(0, poiInfo);
        // results.add(1, poiInfo1);
        location =
                new Location(Constants.location_lat, Constants.location_lon, "", "",
                        Constants.location_city);
        mList.setAdapter(new LocationAdapter(NearLoationActivity.this, results,
                Constants.PAGE_SIZE, R.layout.item_location, R.layout.item_loading));

        if (Constants.location_lat != 4.9E-324 && Constants.location_lon != 4.9E-324) {
            LatLng ptCenter = new LatLng(Constants.location_lat, Constants.location_lon);
            // 反Geo搜索
            mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(ptCenter));
        } else {
            locationManager.startLoacation(NearLoationActivity.this, new IRequest<Location>() {
                @Override
                public void request(Location t) {
                    location = t;
                    // Toast.makeText(getApplicationContext(), t.lat + ":" + t.lon, 0).show();
                    if (t != null && t.lat != 4.9E-324 && t.lon != 4.9E-324) {
                        Constants.location_lat = t.lat;
                        Constants.location_lon = t.lon;
                        Constants.location_address = t.address;
                        Constants.location_city = t.city;
                        LatLng ptCenter = new LatLng(t.lat, t.lon);
                        // 反Geo搜索
                        mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(ptCenter));
                    } else {
                        Toast.makeText(getApplicationContext(), "定位失败", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

    }



    private final OnGetGeoCoderResultListener mOnGetGeoCoderResultListener =
            new OnGetGeoCoderResultListener() {
                @Override
                // 根据地址获取经纬度
                public void onGetGeoCodeResult(GeoCodeResult result) {
                    System.out.println(result);
                }

                @Override
                // 根据经纬度反编译地址
                public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
                    if (progressDialog != null)
                        progressDialog.dismiss();

                    if (result != null && result.getPoiList() != null) {

                        PoiInfo poiInfo = new PoiInfo();
                        poiInfo.name = "不显示位置";
                        result.getPoiList().add(0, poiInfo);
                        if (!TextUtils.isEmpty(Constants.location_city)) {
                            PoiInfo poiInfo1 = new PoiInfo();
                            poiInfo1.name = Constants.location_city;
                            result.getPoiList().add(1, poiInfo1);
                        }
                        mList.setAdapter(new LocationAdapter(NearLoationActivity.this, result
                                .getPoiList(), Constants.PAGE_SIZE, R.layout.item_location,
                                R.layout.item_loading));

                    } else {
                        Toast.makeText(getApplicationContext(), "获取地址失败", Toast.LENGTH_SHORT)
                                .show();
                    }
                }

            };
    private String locationName;
    private ProgressHUD progressDialog;


    class LocationAdapter extends XinDaoBaseAdapter<PoiInfo> {

        public LocationAdapter(Context context, List<PoiInfo> iniData, int pageSize, int res,
                int loadingRes) {
            super(context, iniData, pageSize, res, loadingRes);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent, final PoiInfo value) {
            ViewHolder holder = (ViewHolder) convertView.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.address = (TextView) convertView.findViewById(R.id.address);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                holder.check_address = (ImageView) convertView.findViewById(R.id.check_address);
            }

            holder.address.setText(value.address);
            holder.name.setText(value.name);

            if (locationName.equals(value.name)) {
                holder.check_address.setBackgroundResource(R.drawable.check_address);
            } else {
                holder.check_address.setBackgroundResource(0);
            }

            onclickListener(convertView, holder, value);

            return convertView;
        }

        private void onclickListener(View convertView, final ViewHolder holder, final PoiInfo value) {
            convertView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    holder.check_address.setImageResource(R.drawable.check_address);
                    // setResult(0);
                    Intent data = new Intent();
                    Location mLoacation = null;
                    if (value != null) {
                        mLoacation =
                                new Location(location.lat, location.lon, value.name, value.address,
                                        Constants.location_city == null ? ""
                                                : Constants.location_city);
                    } else {
                        mLoacation =
                                new Location(location.lat, location.lat, location.name,
                                        location.address);
                    }
                    data.putExtra("location", mLoacation);
                    setResult(RESULT_OK, data);
                    NearLoationActivity.this.finish();
                }
            });
        }

        @Override
        public void nextPage(
                int start,
                int size,
                com.xindaoapp.happypet.adapter.XinDaoBaseAdapter.ILoadNextPageData<PoiInfo> iLoadNextPageData) {
            iLoadNextPageData.loadNextPageData(new ArrayList<PoiInfo>());
        }

    }

    class ViewHolder {
        TextView address;
        TextView name;
        ImageView check_address;
    }

    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }

    @Override
    protected OnClickListener getLeftViewClickListener() {

        return new OnClickListener() {

            @Override
            public void onClick(View v) {
                NearLoationActivity.this.finish();
            }
        };
    }

    @Override
    protected void onDestroy() {
        mSearch.setOnGetGeoCodeResultListener(null);
        mSearch.destroy();
        mSearch = null;
        locationManager.stopLocation();
        super.onDestroy();
    }


    @Override
    protected int getTopBarRightTextViewRes() {
        return R.string.location_refresh;
    }

    @Override
    protected OnClickListener getRightViewClickListener() {
        return new OnClickListener() {

            @Override
            public void onClick(View v) {
                // locationManager.stopLocation();
                locationManager.isLoadFirst = true;
                onLoadDatas();
            }
        };
    }

}
